# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
import logging
import time

from django.contrib import auth
from django.http import JsonResponse
from django.middleware import csrf
from django.shortcuts import render


from blueapps.account.decorators import login_exempt
from blueapps.account.forms import LoginForm
from blueapps.middleware.xss.decorators import escape_exempt

logger = logging.getLogger("root")

@login_exempt
def login_success(request):
    """
    弹框登录成功返回页面
    """
    return render(request, "account/login_success.html")


@login_exempt
def login_page(request):
    """
    跳转至固定页面，然后弹框登录
    """
    refer_url = request.GET.get("refer_url")

    context = {"refer_url": refer_url}
    return render(request, "account/login_page.html", context)


@login_exempt
@escape_exempt
def login_forbidden(request):
    """
    跳转至固定页面，拦截登录
    """
    hint_msg = request.GET.get("hint_msg")
    context = {"hint_msg": hint_msg}
    return render(request, "account/login_forbidden.html", context)

@login_exempt
def login(request):

    # yanzg 使用form对象校验输入格式
    form = LoginForm(request.POST)

    if not form.is_valid():
        logger.debug(
            u"[login]登录输入校验异常，url：{}，params：{}, errors: {}".format(
                request.path_info, request.POST, form.errors
            )
        )
        # error ret
        return JsonResponse({
            "code": 46100,
            "data": "null",
            "message": "用户密码输入有误",
        })

    username = form.cleaned_data["username"]
    password = form.cleaned_data["password"]

    # 使用auth backend 查询用户密码
    user = auth.authenticate(request, username=username,password=password)

    if user is None:
        return JsonResponse({
            "code": 401,
            "data": "null",
            "message": "用户密码认证失败",
        })

    # 保存用户session， 执行后 user对象保存在 request.user
    auth.login(request,user)
    return JsonResponse(
        {
            "code": 0,
            "data": {"id": request.user.id, "username": request.user.username, "timestamp": time.time()},
            "message": "ok",
        }
    )

def send_code_view(request):
    ret = request.user.send_code()
    return JsonResponse(ret)


def get_user_info(request):

    return JsonResponse(
        {
            "code": 0,
            "data": {"id": request.user.id, "username": request.user.username, "timestamp": time.time()},
            "message": "ok",
        }
    )


def get_csrf_token(request):
    """
    前端获取csrf_token接口
    """
    csrf_token = csrf.get_token(request)
    return JsonResponse({"csrf_token": csrf_token})
